package com.showcai.controller.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.showcai.log.LogFactory;
import com.showcai.module.wechat.UserWechatInfo;
import com.showcai.redis.RedisCache;
import com.showcai.tools.HttpClientHelper;
import com.showcai.tools.json.JsonHandler;
import com.showcai.util.FixedData;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.Date;
import java.util.Map;

/**
 * Created by Baggio on 2017-3-20.
 */
public class WeChatTools {
/*    @Autowired
    JsapiTicketMapper jsapiTicketMapper;
    @Autowired
RedisCache redisCache;*/

    public static Logger logger = LogFactory.getLogger(HttpClientHelper.class);
    private static  final  Integer EXPIRE=7000;
    public static String getAccessToken() {

        String accessTokenKey = "accessTokenKey_" + FixedData.ENTERPRISE_APP_ID;
        String accessToken = null;
        try {


            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            RedisCache redisCache=  wac.getBean(RedisCache.class);
            accessToken =(String) redisCache.get(accessTokenKey);
            if (StringUtils.isBlank(accessToken)) {
                logger.info("accessToken is null in redies 重新获取accessToken======>>>");
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + FixedData.ENTERPRISE_APP_ID + "&secret=" + FixedData.APP_APPSECRET;
                String dsd = HttpClientHelper.doGet(url);
                logger.info("accessToken====>>>" + dsd);
                JSONObject jon = JSONObject.parseObject(dsd);

                accessToken = (String) jon.get("access_token");
                if (StringUtils.isBlank(accessToken)) {
                    throw new RuntimeException("获取accessToken失败！accessToken is null");
                }
                logger.info("accessToken==is=???>>" + accessToken);
                 redisCache.put(accessTokenKey,accessToken,EXPIRE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取accessToken失败=======》》》》》");
        }

        logger.info("accessToken======>>>" + accessToken);
        return accessToken;
    }

    public static String getTicket() {
        //String  ticketKey = "ticketKey_"+FixedData.ENTERPRISE_APP_ID;
        String ticket = WeiXinUtils.jsTicket.get("ticket");
        String timestamp = WeiXinUtils.jsTicket.get("timestamp");
        Long nowTimestamp = new Date().getTime();
        Long subTimestamp = null;
        try {
            try {
                if (StringUtils.isNotBlank(timestamp)) {
                    Long ticketTimestamp = Long.parseLong(timestamp);
                    if (ticketTimestamp != null) {
                        subTimestamp = nowTimestamp - ticketTimestamp;
                        logger.info("subTimestamp===>>" + subTimestamp);
                    }

                }
            } catch (NumberFormatException e) {
                logger.info("timestamp 转换出错==》》" + timestamp);
                e.printStackTrace();
            }


            /*  ticket =(String) redisCache.get(ticketKey);*/
            if (StringUtils.isBlank(ticket) || (StringUtils.isNotBlank(ticket) && StringUtils.isBlank(timestamp))
                    || (StringUtils.isNotBlank(ticket) && subTimestamp != null && subTimestamp > WeiXinUtils.EXPIREIN)
            ) {
                logger.info("ticket is null in redies 重新获取ticket======>>>" + ticket + "[" + timestamp + "]");
                String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getAccessToken() + "&type=jsapi";
                String dsd = HttpClientHelper.doGet(url);
                logger.info("dsd====>>>" + dsd);
                JSONObject jon = JSONObject.parseObject(dsd);

                ticket = (String) jon.get("ticket");
                if (StringUtils.isBlank(ticket)) {
                    throw new RuntimeException("获取ticket失败！ticket is null");
                }
                logger.info("ticket==is=???>>" + ticket);
                WeiXinUtils.jsTicket.put("ticket", ticket);
                WeiXinUtils.jsTicket.put("timestamp", String.valueOf(nowTimestamp));
                /* redisCache.put(ticketKey,ticket,EXPIRE);*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取ticket失败=======》》》》》" + e.getMessage());


        }

        logger.info("ticket======>>>" + ticket);
        return ticket;
    }


    public static String getopenId(String appId, String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + FixedData.ENTERPRISE_APP_ID + "&secret=" + FixedData.APP_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        String openid = "";
        String accessToken = "";
        String nickname = "";
        UserWechatInfo userWechatInfo=new UserWechatInfo();
        try {
            String dsd = HttpClientHelper.doGet(url);
            logger.info("dsd  jon==>" + dsd.toString());
            JSONObject jon = JSONObject.parseObject(dsd);
            logger.info("getopenId  jon==>" + jon.toString());
            openid = (String) jon.get("openid");
            accessToken = (String) jon.get("access_token");
          //  userWechatInfo=getUserWechatInfo(accessToken,openid);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return openid;
    }
    public static UserWechatInfo getopenId2(String appId, String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + FixedData.ENTERPRISE_APP_ID + "&secret=" + FixedData.APP_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        String openid = "";
        String accessToken = "";
        String nickname = "";
        UserWechatInfo userWechatInfo=new UserWechatInfo();
        try {
            String dsd = HttpClientHelper.doGet(url);
            logger.info("dsd  jon==>" + dsd.toString());
            JSONObject jon = JSONObject.parseObject(dsd);
            logger.info("getopenId  jon==>" + jon.toString());
            openid = (String) jon.get("openid");
            accessToken = (String) jon.get("access_token");
             userWechatInfo=getUserWechatInfo(accessToken,openid);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return userWechatInfo;
    }

    public static UserWechatInfo getUserWechatInfo(String accessToken, String openId) {
        //String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId;
        String url ="https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        logger.info("sendUrl is ==>>"+url);
        UserWechatInfo userWechatInfo = new UserWechatInfo();
        try {
            String getUserWechatInfoJson = HttpClientHelper.doGet(url);
            logger.info("getUserWechatInfoJson==>" + getUserWechatInfoJson);
            getUserWechatInfoJson = new String(getUserWechatInfoJson.getBytes("ISO-8859-1"), "UTF-8");

            userWechatInfo = (UserWechatInfo) JsonHandler.jsonToObject(getUserWechatInfoJson, UserWechatInfo.class);
            logger.info(userWechatInfo.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userWechatInfo;

    }


    public static String weChatQrcode(String distributor_code) {
        String sourceQRCode = "";

        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        JsonObject json = new JsonObject();
        json.addProperty("action_name", "QR_LIMIT_STR_SCENE");

        JsonObject actionInfo = new JsonObject();
        JsonObject scene = new JsonObject();
        scene.addProperty("scene_str", distributor_code);
        actionInfo.add("scene", scene);
        json.add("action_info", actionInfo);

        logger.info(json.toString());
        String jsonTick = HttpClientHelper.stringPost(url, json.toString());
        logger.info(jsonTick);
        Map<String, Object> jsonMap = JsonHandler.json2Map(jsonTick);
        sourceQRCode = (String) jsonMap.get("url");
        logger.info("sourceQRCode====>>>" + sourceQRCode);
        return sourceQRCode;
    }


    public static Map<String, Object> batchgetMaterial(String type, Integer offset) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accessToken;
        JsonObject json = new JsonObject();
        json.addProperty("type", type);
        json.addProperty("offset", offset);
        json.addProperty("count", 20);

        logger.info(json.toString());
        String jsonTick = HttpClientHelper.stringPost(url, json.toString());
        logger.info(jsonTick);

        Map<String, Object> jsonMap = JsonHandler.json2Map(jsonTick);
        logger.info("jsonMap====>>>>" + jsonMap.toString());
        return jsonMap;
    }


}
